package day1.udp.mine;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UdpClient {
    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in);
        System.out.println("DEBUG: 请输入请求数据");
        String request = input.nextLine();

        System.out.println("DEBUG: 将请求数据打包");
        byte[] bytes = request.getBytes("UTF-8");

        System.out.println("DEBUG: 准备发送请求");
        DatagramPacket sent = new DatagramPacket(
                bytes,
                0,
                bytes.length,
                InetAddress.getLoopbackAddress(), // 得到本机地址
                8080
        );
        DatagramSocket socket = new DatagramSocket(9999);
        socket.send(sent);
        System.out.println("DEBUG: 成功发送请求");

        System.out.println("DEBUG: 准备接收响应");
        byte[] buf = new byte[1024];
        DatagramPacket received = new DatagramPacket(buf, buf.length);

        socket.receive(received);       // 服务器会阻塞
        int n = received.getLength();
        String response = new String(buf, 0, n, "UTF-8");
        System.out.println("DEBUG: 收到响应");
        System.out.println(response);
    }
}
